﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace TaxiDispatchClient
{
    public partial class TaxiParametersSetForm : DevExpress.XtraEditors.XtraForm
    {
        public TaxiParametersSetForm()
        {
            InitializeComponent();
        }

        private void TaxiParametersSetForm_Load(object sender, EventArgs e)
        {
            if (MainForm.MyUserInfo.CompanyName != Service.PowerConfig.MainCompanyName)
            {
                radioGroup_SelectType.Properties.Items.RemoveAt(3);
            }             
            _isload = true;
            _thread = new Thread(BindData);
            _thread.Start();
        }

        private Thread _thread;
        private bool _isload;
        private Model.TaxiInfo _model;


        private void BindData()
        {
            string para = radioGroup_SelectType.Properties.Items[
                radioGroup_SelectType.SelectedIndex].Value.ToString();
            string paraValue = textEdit_paraValue.Text;

            StringBuilder strWhere = new StringBuilder();
            if (paraValue.Trim() == "")
            {
                if (MainForm.MyUserInfo.CompanyName!=Service.PowerConfig.MainCompanyName)
                {
                    strWhere.Append("CompanyName='");
                    strWhere.Append(MainForm.MyUserInfo.CompanyName);
                    strWhere.Append("' ");
                }                 
            }
            else
            {
                strWhere.Append(para);
                strWhere.Append(" like '%");
                strWhere.Append(paraValue);
                strWhere.Append("%' ");
                if (MainForm.MyUserInfo.CompanyName != Service.PowerConfig.MainCompanyName)
                {
                    strWhere.Append(" and CompanyName='");
                    strWhere.Append(MainForm.MyUserInfo.CompanyName);
                    strWhere.Append("' ");
                }         
            }
            DataSet ds = MainForm.PositionService.TaxiInfoGetList(strWhere.ToString());
            //DataSet ds = new DataSet();
            //if(textEdit_paraValue.Text.Trim()=="")
            //{
            //    ds = MainForm.PositionService.TaxiInfoGetList("");
            //}
            //else
            //{
            //    string parameter = "";
            //    switch (radioGroup_SelectType.SelectedIndex)
            //    {
            //        case 0:
            //            parameter = "TaxiNo";
            //            break;
            //        case 1:
            //            parameter = "TaxiType";
            //            break;
            //        case 2:
            //            parameter = "Remark";
            //            break;
            //        case 3:
            //            parameter = "Taxigroup";
            //            break;
            //    }
            //    string parameterValue = textEdit_paraValue.Text;
            //    ds = MainForm.PositionService.TaxiInfoGetListWithPar(parameter, parameterValue);                
            //}
            if(ds!=null)
            {
                BeginInvoke(new MethodInvoker(() =>
                {
                    gridControl1.DataSource = ds.Tables[0];
                    gridView1.GroupPanelText = "共计选择 "+ds.Tables[0].Rows.Count+" 辆出租车";
                    if(ds.Tables[0].Rows.Count>0)
                    {
                        gridView1.FocusedRowHandle = 0;                         
                        gridView1_RowClick(null, null);
                        btn_save.Enabled = true;
                    }
                    else
                    {
                        btn_save.Enabled = false;
                    }
                }));                
                if(_isload)
                {
                    SetGridStyle();
                    _isload = false;
                }                
            }
            else
            {
                btn_save.Enabled = false;
            }
            
        }

        private void SetGridStyle()
        {
            //BeginInvoke(new MethodInvoker(() =>
            //{
            //    gridView1.Columns["id"].Visible = false;
            //    gridView1.Columns["TaxiNo"].Caption = "牌照";
            //    gridView1.Columns["TaxiNo"].Width = 80;
            //    gridView1.Columns["TaxiGroupid"].Visible = false;                
            //    gridView1.Columns["TaxiType"].Caption = "型号";
            //    gridView1.Columns["TaxiType"].Width = 90;
            //    gridView1.Columns["Taxigroup"].Caption = "分组";
            //    gridView1.Columns["Taxigroup"].Width = 90;
            //    gridView1.Columns["Remark"].Caption = "所属公司";
              
            //    //gridView1.Columns["SpeedOut"].Caption = "超速时速(公里/小时)";
            //    //gridView1.Columns["SpeedOutIsOpen"].Caption = "超速报警是否启用";
            //    //gridView1.Columns["StopTimeOut"].Caption = "超时停车时间(单位:10分钟)";
            //    //gridView1.Columns["StopTimeOutIsOpen"].Caption = "超时停车报警是否启用";
            //    //gridView1.Columns["FatigueDrivingTime"].Caption = "剩余工作时间(单位：分钟)";
            //    //gridView1.Columns["FatigueDrivingIsOpen"].Caption = "低电量报警是否启用";
            //}));           
        }

        private void btn_select_Click(object sender, EventArgs e)
        {
            _thread = new Thread(BindData);
            _thread.Start();
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            _thread = new Thread(BindCurrentRow);
            _thread.Start();
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {           
            _thread = new Thread(BindCurrentRow);
            _thread.Start();
        }


        private void BindCurrentRow() 
        {
            DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            if (row == null) return;
            int id = int.Parse(row["id"].ToString());           
            Model.TaxiInfo model = MainForm.PositionService.TaxiGetModel(id);
            _model = model;
            if (model != null)
            {               
                BeginInvoke(new MethodInvoker(() =>
                                                  {
                                                      if (radioGroup_object.SelectedIndex == 0)
                                                      {
                                                          label_taxiNo.Text = row["TaxiNo"].ToString();
                                                      }

                                                      textEdit_power.Text = model.FatigueDravingTime.ToString();
                                                      textEdit_speed.Text = model.SpeedOut.ToString();
                                                      textEdit_stopTimeOut.Text = model.StopOutTime.ToString();
                                                      checkEdit_power.CheckState = model.FatigueDravingIsOpen == 1 ?
                                                          CheckState.Checked : CheckState.Unchecked;
                                                      checkEdit_speed.CheckState = model.SpeedOutIsOpen == 1 ?
                                                          CheckState.Checked : CheckState.Unchecked;
                                                      checkEdit_stopTimeOut.CheckState = model.StopOutIsOpen == 1 ?
                                                          CheckState.Checked : CheckState.Unchecked;
                                                  }));
             
            }
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            if (btn_save.Tag.ToString() == "保存")
            {          
                if(!CheckPassed()) return;
               
                //修改当前选中的一辆出租车
                if(radioGroup_object.SelectedIndex ==0)
                {
                    if(XtraMessageBox.Show("是否修改车牌号为 "+label_taxiNo.Text+" 的出租车告警配置",
                        "修改确认：",MessageBoxButtons.OKCancel)== DialogResult.Cancel)
                        return;
                    UpdateModel(_model);
                }
                //修改当前列表中所有出租车
                else
                {
                 if (XtraMessageBox.Show("是否修列表中所有出租车（共" +gridView1.DataRowCount +
                     "辆）的告警配置",
                        "修改确认：", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                     return;
                  progressBar1.Position = 0;
                  progressBar1.Visible = true;
                  btn_save.Enabled = false;
                  _thread = new Thread(UpdateTaxisInGridView);
                  _thread.Start();
                }
                btn_save.Tag = "修改";
                btn_save.Image = Properties.Resources.UserForm_btnmodify001;
                btn_cancel.Visible = false;
                ResetControl(false);
            }
            else
            {
                ResetControl(true);
                textEdit_power.Focus();
                btn_save.Tag = "保存";
                btn_save.Image = Properties.Resources.UserForm_btnsave001;
                btn_cancel.Visible = true;
            }
        }

        private void UpdateTaxisInGridView()
        {
            int count = gridView1.DataRowCount;
            BeginInvoke(new MethodInvoker(() =>
                                              {
                                                  progressBar1.Properties.Maximum = count;                                                                             
                                              }));            
            
            int falsed = 0;
            for (int i = 0; i < gridView1.DataRowCount; i++)
            {
                DataRow row = gridView1.GetDataRow(i);
                int id = int.Parse(row["id"].ToString());
                Model.TaxiInfo model = MainForm.PositionService.TaxiGetModel(id);
                if(!UpdateModel(model))
                falsed ++;
                BeginInvoke(new MethodInvoker(() =>
                {
                    progressBar1.Position++;                    
                }));
            }
            XtraMessageBox.Show("共计成功更新" + (count - falsed) 
                + "条，失败" + falsed + "条记录");
            BeginInvoke(new MethodInvoker(() =>
                                              {
                                                  progressBar1.Visible = false;
                                                  btn_save.Enabled = true;
                                              }));

        }

        private bool UpdateModel(Model.TaxiInfo model)
        {
            model.FatigueDravingTime = int.Parse(textEdit_power.Text);
            model.FatigueDravingIsOpen = checkEdit_power.CheckState==CheckState.Checked?1:0;
            model.StopOutTime = int.Parse(textEdit_stopTimeOut.Text);
            model.StopOutIsOpen = checkEdit_stopTimeOut.CheckState == CheckState.Checked ? 1 : 0;
            model.SpeedOut = int.Parse(textEdit_speed.Text);
            model.SpeedOutIsOpen = checkEdit_speed.CheckState==CheckState.Checked ? 1 : 0;
            return MainForm.PositionService.TaxiInfoUpdate(model);
        }


        private bool CheckPassed()
        {
           if(textEdit_speed.Text.Trim()=="")
           {
               XtraMessageBox.Show("超速速度不能为空！");
               textEdit_speed.Focus();
               return false;
           }
           if (textEdit_speed.Text.Trim() == "0")
           {
               XtraMessageBox.Show("超速速度需大于0！");
               textEdit_speed.Focus();
               return false;
           }           
           if (textEdit_stopTimeOut.Text.Trim() == "")
           {
               XtraMessageBox.Show("超时停车时间不能为空！");
               textEdit_stopTimeOut.Focus();
               return false;
           }
           if (textEdit_stopTimeOut.Text.Trim() == "0")
           {
               XtraMessageBox.Show("超时停车时间需大于0！");
               textEdit_stopTimeOut.Focus();
               return false;
           }
           if (textEdit_power.Text.Trim() == "")
           {
               XtraMessageBox.Show("电池剩余时间不能为空！");
               textEdit_power.Focus();
               return false;
           }
           if (textEdit_power.Text.Trim() == "0")
           {
               XtraMessageBox.Show("电池剩余时间需大于0");
               textEdit_power.Focus();
               return false;
           }
           return true;
        }
        

        private void ResetControl(bool enable)
        {
            textEdit_speed.Enabled = enable;
            textEdit_power.Enabled = enable;
            textEdit_stopTimeOut.Enabled = enable;
            checkEdit_speed.Enabled = enable;
            checkEdit_stopTimeOut.Enabled = enable;
            checkEdit_power.Enabled = enable;
            radioGroup_object.Enabled = enable;
        }

        #region 窗体控件效果
        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }
        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void PhoneUserForm_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
        #endregion

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            btn_cancel.Visible = false;
            ResetControl(false);
            btn_save.Tag = "修改";
            btn_save.Image = Properties.Resources.UserForm_btnmodify001;
            BindCurrentModel();
        }

        private void BindCurrentModel()
        {
            if(_model!=null)
            {
                label_taxiNo.Text = _model.TaxiNo;
                textEdit_speed.Text = _model.SpeedOut.ToString();
                checkEdit_speed.CheckState =_model.SpeedOutIsOpen == 1
                                                       ? CheckState.Checked :
                                                       CheckState.Unchecked;
                textEdit_stopTimeOut.Text = _model.StopOutTime.ToString();
                checkEdit_stopTimeOut.CheckState = _model.StopOutIsOpen == 1
                                                       ? CheckState.Checked
                                                       : CheckState.Unchecked;
                textEdit_power.Text = _model.FatigueDravingTime.ToString();
                checkEdit_power.CheckState =_model.FatigueDravingIsOpen == 1
                                                          ? CheckState.Checked
                                                          : CheckState.Unchecked;            
            }            
        }

       

        private void radioGroup_object_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(radioGroup_object.SelectedIndex ==0)
            {
                if(_model!=null)
                {
                    label_taxiNo.Text = _model.TaxiNo;
                }
                else
                {
                    label_taxiNo.Text = "未选择";
                }
            }
            else
            {
                label_taxiNo.Text = "列表中的"+gridView1.DataRowCount+"出租车";
            }
        }
    }
}